package com.huanletao.tran;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Component
public class UserService {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    PlatformTransactionManager transactionManager;
    @Autowired
    TransactionTemplate transactionTemplate;

    /**
     * 声明事务；
     */
    @Transactional
    public void transfer3() {
      jdbcTemplate.update("update user set mony = ? where username=?", 12, "zhangsan");
        int i = 1/0;
    }

    /**
     * TransactionTemplate 实现编程事务；
     */
    public void transfer2() {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    int i = jdbcTemplate.update("update user set mony = ? where username=?", 9, "zhangsan");
                } catch (DataAccessException e) {
                    e.printStackTrace();
                    status.setRollbackOnly();
                }
            }
        });
    }

    /**
     * PlatformTransactionManager 实现编程事务；
     */
    public void transfer() {
        DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(definition);
        try {
            int i = jdbcTemplate.update("update user set mony = ? where username=?", 9, "zhangsan");
            transactionManager.commit(status);
        } catch (DataAccessException e) {
            e.printStackTrace();
            transactionManager.rollback(status);
        }
    }

}
